package cn.xiaopengstack.trigger.http;

import cn.xiaopengstack.api.dto.HomePageRequestDTO;
import cn.xiaopengstack.api.dto.HomePageResponseDTO;
import cn.xiaopengstack.api.dto.UserGroupBuyOrderDTO;
import cn.xiaopengstack.api.service.IHomePageService;
import cn.xiaopengstack.domain.activity.model.entity.*;
import cn.xiaopengstack.domain.activity.model.valobj.UserGroupBuyOrderVO;
import cn.xiaopengstack.domain.activity.service.trialcal.IIndexGroupBuyMarketService;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangyangang
 */
@Slf4j
@RestController
@RequestMapping("/api/${app.config.api-version}/group-buy-market/home-page/")
@CrossOrigin("*")
public class IHomePageController implements IHomePageService {


    @Resource
    private IIndexGroupBuyMarketService indexGroupBuyMarketService;


    @PostMapping("query_goods_group_buy_info")
    @Override
    public Response<HomePageResponseDTO> queryGoodsGroupBuyInfo(@RequestBody HomePageRequestDTO requestDTO) {
        log.info("查询拼团营销配置开始:{} goodsId:{}", requestDTO.getUserId(), requestDTO.getGoodsId());

        if (StringUtils.isBlank(requestDTO.getUserId()) || StringUtils.isBlank(requestDTO.getSource()) || StringUtils.isBlank(requestDTO.getChannel()) || StringUtils.isBlank(requestDTO.getGoodsId())) {
            return Response.error(null, ResponseCode.ILLEGAL_PARAMETER);
        }

        try {
            // 拼团试算
            TrialCalculateEntity trialCalculateEntity = indexGroupBuyMarketService.trialCalculate(MarketProductEntity.builder()
                    .goodsId(requestDTO.getGoodsId())
                    .channel(requestDTO.getChannel())
                    .source(requestDTO.getSource())
                    .userId(requestDTO.getUserId())
                    .build());

            // 拼团队伍信息
            List<GroupBuyOrderDetailEntity> groupBuyOrderDetailEntities = indexGroupBuyMarketService.queryInProgressGroupOrderList(QueryInProgressGroupBuyOrderEntity
                    .builder()
                    .count(2)
                    .activityId(trialCalculateEntity.getActivityId())
                    .source(requestDTO.getSource())
                    .channel(requestDTO.getChannel())
                    .goodsId(requestDTO.getGoodsId())
                    .build());

            // 拼团统计信息
            TeamStatisticEntity teamStatisticEntity = indexGroupBuyMarketService.queryTeamStatistic(trialCalculateEntity.getActivityId(), requestDTO.getGoodsId());

            // 参数组装
            HomePageResponseDTO.Goods goods = HomePageResponseDTO.Goods.builder()
                    .deductionPrice(trialCalculateEntity.getDeductionPrice())
                    .originalPrice(trialCalculateEntity.getOriginalPrice())
                    .payPrice(trialCalculateEntity.getPayPrice())
                    .goodsId(trialCalculateEntity.getGoodsId())
                    .goodsName(trialCalculateEntity.getGoodsName())
                    .build();

            HomePageResponseDTO.TeamStatistic teamStatistic = HomePageResponseDTO.TeamStatistic.builder()
                    .allTeamCompleteCount(teamStatisticEntity.getAllTeamCompleteCount())
                    .allTeamCount(teamStatisticEntity.getAllTeamCount())
                    .allTeamUserCount(teamStatisticEntity.getAllTeamUserCount())
                    .build();


            List<HomePageResponseDTO.Team> teamList = groupBuyOrderDetailEntities.stream().map(detail -> {
                Long groupBuyEndLeftTime = detail.getGroupEndTime().toInstant().toEpochMilli() - LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

                return HomePageResponseDTO.Team.builder()
                        .teamId(detail.getTeamId())
                        .groupBuyEndTime(detail.getGroupEndTime().toInstant().toEpochMilli())
                        .groupBuyStartTime(detail.getGroupStartTime().toInstant().toEpochMilli())
                        .groupBuyEndLeftTime(groupBuyEndLeftTime)
                        .completeCount(detail.getCompleteCount())
                        .lockCount(detail.getLockCount())
                        .targetCount(detail.getTargetCount())
                        // 拼团名字暂时写成用户ID，原预期：蒋小鹏的拼团
                        .teamName(detail.getUserId() + "的拼团队伍")
                        .build();
            }).collect(Collectors.toList());


            HomePageResponseDTO.Activity activity = HomePageResponseDTO.Activity.builder()
                    .activityId(trialCalculateEntity.getActivityId())
                    .build();

            return Response.success(HomePageResponseDTO.builder()
                    .goods(goods)
                    .teamStatistic(teamStatistic)
                    .teamList(teamList)
                    .activity(activity)
                    .build());

        } catch (Exception e) {
            log.error("查询商品拼团信息异常", e);
            return Response.error(null, ResponseCode.UN_ERROR);
        }
    }

    /**
     * 查询用户已参与的拼团订单
     * @param userId
     * @return
     */
    @PostMapping("query_order_list")
    @Override
    public Response<List<UserGroupBuyOrderDTO>> queryUserGroupBuyOrders(@RequestParam("userId") String userId) {

        List<UserGroupBuyOrderVO> groupBuyOrderVOList = indexGroupBuyMarketService.queryUserGroupBuyList(userId);

        List<UserGroupBuyOrderDTO> responseList = groupBuyOrderVOList
                .stream().map((orderVO) -> UserGroupBuyOrderDTO
                        .builder()
                        .orderId(orderVO.getOrderId())
                        .orderStatus(orderVO.getOrderStatus())
                        .currentTeamNumber(orderVO.getCurrentTeamNumber())
                        .remainingTeamNumber(orderVO.getRemainingTeamNumber())
                        .teamStatus(orderVO.getTeamStatus())
                        .activityId(orderVO.getActivityId())
                        .build()).toList();

        return Response.success(responseList);
    }

    public static void main(String[] args) {

        System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
    }
}
